package metadata

import (
	"context"
	"fmt"
	"math/rand"
	"time"

	clientv3 "go.etcd.io/etcd/client/v3"
)

func GetRPCAddressFromEtcd(servers []string, key string) (string, error) {
	rand.Seed(time.Now().UnixNano())
	serverIndex := rand.Intn(len(servers))
	server := servers[serverIndex]

	// 配置客户端
	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   []string{server},
		DialTimeout: 5 * time.Second,
	})
	if err != nil {
		return "", err
	}
	//defer cli.Close()

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	// 2. 获取键值对
	resp, err := cli.Get(ctx, key, clientv3.WithPrefix())
	if err != nil {
		return "", err
	}

	var instances []string
	for _, ev := range resp.Kvs {
		instances = append(instances, string(ev.Value))
	}
	if len(instances) == 0 {
		return "", fmt.Errorf("no instances found for key: %s", key)
	}

	instanceIndex := rand.Intn(len(instances))
	return instances[instanceIndex], nil
}
